import React, { createContext, useContext, useState, useEffect } from 'react';
import type { ReactNode } from 'react';
import type { Current } from '../types/typeings';
import request from '../utils/request';

// 发送验证码函数
export const sendCode = async (account: string, type: 'email' | 'phone') => {
  try {
    return await request.post<any>('/auth/send-code', { account, type });
  } catch (error) {
    console.error('发送验证码失败:', error);
    throw error;
  }
};

// 应用状态接口
interface AppState {
  // 用户相关状态
  userState: Current.UserState;
  // 主题相关状态
  themeConfig: Current.ThemeConfig;
  // 用户相关方法
  login: (credentials: { username: string; password: string }) => Promise<void>;
  loginByCode: (credentials: { account: string; code: string; type: 'email' | 'phone' }) => Promise<void>;
  logout: () => void;
  clearError: () => void;
  // 主题相关方法
  updateTheme: (theme: Partial<Current.ThemeConfig>) => void;
  resetTheme: () => void;
}

// 创建Context
const AppContext = createContext<AppState | undefined>(undefined);

// 默认主题配置
const defaultTheme: Current.ThemeConfig = {
  colorPrimary: '#1890ff',
  borderRadius: 6,
};

// 默认用户状态
const defaultUserState: Current.UserState = {
  user: null,
  token: '',
  isLogin: false,
  loading: false,
  error: null,
};

// Context Provider组件
interface AppContextProviderProps {
  children: ReactNode;
}

export const AppContextProvider: React.FC<AppContextProviderProps> = ({ children }) => {
  const [userState, setUserState] = useState<Current.UserState>(defaultUserState);
  const [themeConfig, setThemeConfig] = useState<Current.ThemeConfig>(defaultTheme);

  // 初始化时从本地存储加载用户信息
  useEffect(() => {
    const savedUser = localStorage.getItem('user');
    if (savedUser) {
      try {
        const parsedUser = JSON.parse(savedUser);
        // 检查是否过期
        if (parsedUser.expireTime && parsedUser.expireTime > Date.now()) {
          setUserState({
            user: parsedUser.user,
            token: parsedUser.token,
            isLogin: true,
            loading: false,
            error: null,
          });
        } else {
          // 已过期，清除
          localStorage.removeItem('user');
        }
      } catch (error) {
        console.error('解析用户信息失败:', error);
        localStorage.removeItem('user');
      }
    }
  }, []);

  // 登录方法
  const login = async (credentials: { username: string; password: string }) => {
    setUserState(prev => ({ ...prev, loading: true, error: null }));
    try {
      // 直接使用/auth/login路径，让请求拦截器自动处理前缀
      // 使用类型断言避免TypeScript类型错误
      const response = await request.post<any>('/auth/login', credentials);
      console.log('登录响应:', response);
      // 支持mock返回的标准格式 { success, data, message }
      const responseData = response as any;
      
      // 检查是否成功
      if (responseData.success === false) {
        throw new Error(responseData.message || '登录失败');
      }
      
      // 获取token和user信息
      let token: string | undefined;
      let user: any;
      
      // 首先尝试从data.data中获取（标准格式）
      if (responseData.data && responseData.data.token && responseData.data.user) {
        token = responseData.data.token;
        user = responseData.data.user;
      } else if (responseData.token && responseData.user) {
        // 直接从responseData中获取
        token = responseData.token;
        user = responseData.user;
      }
      
      if (!token || !user) {
        throw new Error('登录失败，返回数据格式不正确');
      }
      
      // 更新状态
      setUserState({
        user,
        token,
        isLogin: true,
        loading: false,
        error: null,
      });

      // 保存到本地存储
      localStorage.setItem('user', JSON.stringify({
        token,
        user,
        expireTime: Date.now() + 7 * 24 * 60 * 60 * 1000 // 7天过期
      }));
    } catch (error: any) {
      setUserState(prev => ({
        ...prev,
        loading: false,
        error: error.response?.data?.message || '登录失败'
      }));
      throw error;
    }
  };

  // 验证码登录方法
  const loginByCode = async (credentials: { account: string; code: string; type: 'email' | 'phone' }) => {
    setUserState(prev => ({ ...prev, loading: true, error: null }));
    try {
      // 使用验证码登录接口
      const response = await request.post<any>('/auth/login-by-code', credentials);
      
      // 支持mock返回的标准格式 { success, data, message }
      const responseData = response as any;
      
      // 检查是否成功
      if (responseData.success === false) {
        throw new Error(responseData.message || '登录失败');
      }
      
      // 获取token和user信息
      let token: string | undefined;
      let user: any;
      
      // 首先尝试从data.data中获取（标准格式）
      if (responseData.data && responseData.data.token && responseData.data.user) {
        token = responseData.data.token;
        user = responseData.data.user;
      } else if (responseData.token && responseData.user) {
        // 直接从responseData中获取
        token = responseData.token;
        user = responseData.user;
      }
      
      if (!token || !user) {
        throw new Error('登录失败，返回数据格式不正确');
      }
      
      // 更新状态
      setUserState({
        user,
        token,
        isLogin: true,
        loading: false,
        error: null,
      });

      // 保存到本地存储
      localStorage.setItem('user', JSON.stringify({
        token,
        user,
        expireTime: Date.now() + 7 * 24 * 60 * 60 * 1000 // 7天过期
      }));
    } catch (error: any) {
      setUserState(prev => ({
        ...prev,
        loading: false,
        error: error.response?.data?.message || '登录失败'
      }));
      throw error;
    }
  };
  const logout = () => {
    setUserState(defaultUserState);
    localStorage.removeItem('user');
  };

  // 清除错误
  const clearError = () => {
    setUserState(prev => ({ ...prev, error: null }));
  };

  // 更新主题
  const updateTheme = (theme: Partial<Current.ThemeConfig>) => {
    setThemeConfig(prev => ({ ...prev, ...theme }));
  };

  // 重置主题
  const resetTheme = () => {
    setThemeConfig(defaultTheme);
  };

  const value: AppState = {
    userState,
    themeConfig,
    login,
    loginByCode,
    logout,
    clearError,
    updateTheme,
    resetTheme,
  };

  return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
};

// 自定义Hook用于使用Context
export const useAppContext = () => {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useAppContext必须在AppContextProvider内部使用');
  }
  return context;
};